package edu.sias.user.utils;

import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;

/**
 * Elasticsearch 工具类（Spring 管理生命周期）
 */
@Component
public class Esutils {

    private RestHighLevelClient client;

    /**
     * 初始化客户端（可配置化改造后应从配置读取 host）
     */
    @PostConstruct
    public void init() {
        this.client = new RestHighLevelClient(
                RestClient.builder(HttpHost.create("http://127.0.0.1:9200"))
        );
    }

    /**
     * 插入文档到指定索引
     *
     * @param index 索引名称
     * @param id    文档ID
     * @param text  要插入的文本内容
     */
    public void add(String index, String id, String text) throws IOException {
        XContentBuilder contentBuilder = XContentFactory.jsonBuilder()
                .startObject()
                .field("text", text)
                .endObject();

        IndexRequest request = new IndexRequest(index)
                .id(id)
                .source(contentBuilder);

        try {
            client.index(request, RequestOptions.DEFAULT);
            System.out.println("文档已插入");
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 销毁客户端（释放资源）
     */
    @PreDestroy
    public void destroy() {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
